package com.demo.auth.controller;

import com.demo.auth.entity.User;
import com.demo.auth.enums.Role;
import com.demo.auth.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    private final UserService userService;

    public AdminController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        // 清除密码信息
        users.forEach(user -> user.setPassword(null));
        return ResponseEntity.ok(users);
    }

    @GetMapping("/users/role/{role}")
    public ResponseEntity<List<User>> getUsersByRole(@PathVariable String role) {
        try {
            Role userRole = Role.fromCode(role.toUpperCase());
            List<User> users = userService.getUsersByRole(userRole);
            // 清除密码信息
            users.forEach(user -> user.setPassword(null));
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/users/{userId}/role")
    public ResponseEntity<?> updateUserRole(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        try {
            String roleCode = request.get("role");
            if (roleCode == null) {
                return ResponseEntity.badRequest().body(Map.of("message", "角色不能为空"));
            }
            
            Role role = Role.fromCode(roleCode.toUpperCase());
            userService.updateUserRole(userId, role);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户角色更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PutMapping("/users/{userId}/status")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long userId, @RequestBody Map<String, Boolean> request) {
        try {
            Boolean enabled = request.get("enabled");
            if (enabled == null) {
                return ResponseEntity.badRequest().body(Map.of("message", "状态不能为空"));
            }
            
            userService.updateUserEnabled(userId, enabled);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", enabled ? "用户已启用" : "用户已禁用");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @GetMapping("/dashboard")
    public ResponseEntity<?> getAdminDashboard() {
        try {
            List<User> allUsers = userService.getAllUsers();
            List<User> admins = userService.getUsersByRole(Role.ADMIN);
            List<User> users = userService.getUsersByRole(Role.USER);
            
            Map<String, Object> dashboard = new HashMap<>();
            dashboard.put("totalUsers", allUsers.size());
            dashboard.put("adminCount", admins.size());
            dashboard.put("userCount", users.size());
            dashboard.put("enabledUsers", allUsers.stream().mapToInt(u -> u.getEnabled() ? 1 : 0).sum());
            
            return ResponseEntity.ok(dashboard);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}